package com.hlz.rabbit.mq.confirm;

import com.hlz.rabbit.mq.util.RabbitMqUtils;
import com.rabbitmq.client.Channel;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 单个确认发布缺点： 发布速度特别的慢，因为如果没有确认发布的消息就会
 * 阻塞所有后续消息的发布
 *
 * @author Hongliang Zhu
 * @create 2022-11-28 23:02
 */
public class PubModConfirmProducer {
    public static void main(String[] args) {

        try (Channel channel = RabbitMqUtils.getChannel()) {

            // 开启发布确认
            channel.confirmSelect();
            channel.queueDeclare("queue-pub-confirm", false, false, false, null);
            long start = System.currentTimeMillis();
            for (int i = 0; i < 200; i++) {
                String message = "confirm" + i;
                channel.basicPublish("", "queue-pub-confirm", null, message.getBytes());
                boolean flag = channel.waitForConfirms();
                if (flag) {
                    System.out.println("消息：" + message + "发送成功..");
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("发布200个单独确认消息,耗时" + (end - start) +
                    "ms");
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
